const pagesConfig = require('./pages') // 多页面配置

const isProduction = process.env.NODE_ENV === 'production' //判断是否为build生产环境

const pageBaseDir = 'portal/pages/dist/'
// 打包目标文件
const distBaseDir = `dist/${pageBaseDir}`
// const distBaseDir = `dist/`
// 静态文件的路径[生产环境使用绝对路径，方便后端做forward，避免css404]
// 命令行参数
const getPage = () => {
    // console.log('process.env.npm_config_argv==>',process.argv);
    let argvs = {}
    let commandArgs = []
    if (process.env.npm_config_argv != undefined) {
        argvs = JSON.parse(process.env.npm_config_argv)
        commandArgs = argvs.original
    } else {
        commandArgs = process.argv
    }
    for (let i = 0; i < commandArgs.length; i++) {
        const item = commandArgs[i]
        if (item.indexOf('--page:') === 0) {
            return item.substr('--page:'.length)
        }
        if (item.indexOf('serve:') === 0) {
            return item.substr('serve:'.length)
        }
    }
    return ''
}

const page = getPage()
let pages = {}
if (!isProduction) {
    if (page == '') {
        const pageKeys = Object.keys(pagesConfig).join(', ')
        throw new Error(`请指定打开页面--page: 已知页面：${pageKeys}`)
    }
    const _configPages = pagesConfig[page].pages
    Object.keys(_configPages).forEach((item, index) => {
        if (index === 0) {
            //默认第一个为index
            pages['index'] = _configPages[item]
        } else {
            // 热加载不支持'/'
            const itemKey = item.replace(/\//g, '$')
            pages[itemKey] = _configPages[item]
        }
    })
} else {
    Object.keys(pagesConfig).map((k1) => {
        const moduleConfig = pagesConfig[k1]
        const module = moduleConfig.module
        const modulePages = moduleConfig.pages
        let targetPages = {}
        Object.keys(modulePages).forEach((key) => {
            if (module === '') {
                targetPages[`${key}`] = modulePages[key]
            } else {
                targetPages[`${module}/${key}`] = modulePages[key]
            }
        })
        pages = { ...pages, ...targetPages }
    })
}

module.exports = {
    buidPages: pages,
    isProduction,
    buildOutPath: distBaseDir,
}
